package com.person.ntv.controller.sys;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import tk.mybatis.mapper.util.StringUtil;

import com.github.pagehelper.Page;
import com.person.Constants;
import com.person.common.PageParams;
import com.person.exception.ServiceException;
import com.person.ntv.entity.sys.SysFile;
import com.person.ntv.entity.sys.SysUser;
import com.person.ntv.service.sys.SysFileService;
import com.person.string.UUIDUtil;

@Controller
@RequestMapping("/system/sysFile")
public class SysFileController {
	@Autowired
		private SysFileService  sysFileService ;
		
		@RequestMapping("/listPage")
		public String  getSysFilePage(HttpServletRequest request,ModelMap mv)throws Exception{
			initCode(mv);
			return "/system/file/fileList";
		}
		
		@RequestMapping("/fileList")
		@ResponseBody
		public Map<String,Object> getSysFileList(PageParams myPage){
			Map<String,Object> map=new HashMap<String,Object>();
			Page<SysFile> page=sysFileService.getFilePage(myPage);
	        map.put("total",page.getTotal());
	        map.put("rows",page.getResult());
			return map;
		}
		
		@RequestMapping("/fileListByFUUID")
		@ResponseBody
		public Map<String,Object> fileListByFUUID(String fuuid){
			Map<String,Object> map=new HashMap<String,Object>();
			List<SysFile>fileList = sysFileService.selectFilesByFUUID(fuuid);
	        map.put("total",fileList.size());
	        map.put("rows",fileList);
			return map;
		}
		
		@RequestMapping("/fileUpload")
		@ResponseBody
		public Map<String,Object>fileUpload(PageParams myPage,HttpServletRequest request) throws Exception{
			//获取当前登录用户
			SysUser sysUser=(SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
			//创建一个通用的多部分解析器  
	        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	        //判断 request 是否有文件上传,即多部分请求  
	        if(multipartResolver.isMultipart(request)){  
	            //转换成多部分request
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            //取得request中的所有文件名  
	            Iterator<String> iter = multiRequest.getFileNames();
	            String uuid=request.getParameter("foreignUuid");
	            while(iter.hasNext()){  
	               //记录上传过程起始时的时间，用来计算上传时间  
	               // int pre = (int) System.currentTimeMillis();  
	                //取得上传文件  
	                MultipartFile file = multiRequest.getFile(iter.next());
	                if(file != null&&file.getSize()>0){
	                	String fileName=file.getOriginalFilename();
	                	String fileNewname=UUIDUtil.getUUID()+fileName.substring(fileName.lastIndexOf("."));
	                	SysFile sysFile=new SysFile();
	                	sysFile.setOriginalName(fileName);
	                	sysFile.setNewName(fileNewname);
	                	sysFile.setStoragePath("");
	                	sysFile.setUploader(sysUser.getUserName());
	                	sysFile.setUploadTime(new Date());
	                	sysFile.setForeignUuid(uuid);
	                	sysFileService.insert(sysFile);
	                }
	            }
	        }
			return null;
		}
		
		@RequestMapping("/addPage")
		public String  addFilePage(ModelMap mv,HttpServletRequest request) throws Exception{
			initCode(mv);
			String foreignUuid = request.getParameter("foreignUuid");
			String extensions = request.getParameter("extensions");
		    String mimeTypes = request.getParameter("mimeTypes");
			if(StringUtils.isEmpty(foreignUuid))
			mv.addAttribute("foreignUuid", UUIDUtil.getUUID());
			else
			mv.addAttribute("foreignUuid",request.getParameter("foreignUuid"));
			mv.addAttribute("extensions",extensions==null?"":extensions);
			mv.addAttribute("mimeTypes",mimeTypes==null?"":mimeTypes);
			return "/system/file/fileAdd";
		}
		
		
		@RequestMapping("/delFileByIds")
		@ResponseBody
		public Map<String,Object>  delFileByIds(BigDecimal[]ids,HttpServletRequest request) throws Exception{
			Map<String,Object> map=new HashMap<String,Object>();
			try {
				sysFileService.delFilesByIds(ids);
				map.put("error", "0");
				map.put("msg","删除成功！");
			} catch (ServiceException e) {
				map.put("error", "1");
				map.put("msg",e.getMessage()+"删除失败！");
			}
			return map;
		}
		@RequestMapping("/delFileByFUUID")
		@ResponseBody
		public Map<String,Object>  delFileByFUUID(String fuuid,HttpServletRequest request) throws Exception{
			Map<String,Object> map=new HashMap<String,Object>();
			try {
				sysFileService.delFilesByFUUID(fuuid);
				map.put("error", "0");
				map.put("msg","删除成功！");
			} catch (ServiceException e) {
				map.put("error", "1");
				map.put("msg",e.getMessage()+"删除失败！");
			}
			return map;
		}
		@RequestMapping("/detailPage")
		public String  detailUserSetPage(String id,ModelMap mv) throws Exception{
			try {
		        mv.addAttribute("sysFile",sysFileService.selectByPrimaryKey(new BigDecimal(id)));
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"查询出错！");
			}
			return "/system/file/fileDetail";
		}
		
		
		private void initCode(ModelMap mv){
			 
		}

}
